var zNodes=new Array();
var webName = "/cms/coll";
$(function(){
	getNodes();
})
//hasItem为true 则为父亲节点 可以有子节点
function getNodes(){
	$.getJSON(webName+"/usertype",{},function(result){
		zNodes.push({ id:1, pId:0, name:"文章类型", open:true,isParent:true,
		iconOpen:"/cms/resources/ztree/cssztree/zTreeStyle/img/diy/1_close.png",
		iconClose:"/cms/resources/ztree/cssztree/zTreeStyle/img/diy/1_open.png"});
		var nodeList = result.data.list;
		for(var i=0;i<nodeList.length;i++){
			if(nodeList[i].hasItem){
				var flag=true; //身为父亲节点 true:没有子节点   false:有子节点
				for(var j=0;j<nodeList.length;j++){
					if(nodeList[i].id==nodeList[j].pid){
						flag==false;
						break;
					}
				}
				if(flag){
					zNodes.push({id:nodeList[i].id,pId:nodeList[i].pid,name:nodeList[i].name,open:true,isParent:true,
						iconOpen:"/cms/resources/ztree/cssztree/zTreeStyle/img/diy/1_close.png",
						iconClose:"/cms/resources/ztree/cssztree/zTreeStyle/img/diy/1_open.png"});
				}
			}else{
				zNodes.push({id:nodeList[i].id,pId:nodeList[i].pid,name:nodeList[i].name,
				icon:"/cms/resources/ztree/cssztree/zTreeStyle/img/diy/2.png"});
			}

		}
		initTree();
	})
	
}
function initTree(){
	var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            check: {
                enable: false,
                chkboxType: {"Y":"s","N":"s"}
            },
            data: {
				key: {
					title:"t"
				},
                simpleData: {
                    enable: true
                },
                keep: {
                	parent: true
                }
            },
            edit: {
                enable: true,
				editNameSelectAll: true,
				showRemoveBtn: showRemoveBtn,
				showRenameBtn: showRenameBtn,
				drag: {
					autoExpandTrigger: true,
					prev: false,
					next: false,
					inner: true
				}
            },
			callback: {				
				//展开收起
				beforeCollapse: beforeCollapse,
				beforeExpand: beforeExpand,
				onCollapse: onCollapse,
				onExpand: onExpand,
				//checkbox 保留
//				beforeCheck: beforeCheck,
//				onCheck: onCheck,
				//删除 修改
				beforeEditName: beforeEditName,
				beforeRename: beforeRename,
				onRename: onRename,
				beforeRemove: beforeRemove,
				onRemove: onRemove,
				//拖拽
				beforeDrag: beforeDrag,
				beforeDrop: beforeDrop,
				beforeDragOpen: beforeDragOpen,
				onDrag: onDrag,
				onExpand: onExpand,
				//点击
				beforeClick: beforeClick,
				onClick: onClick
			}
        };
		
        
      //--------------鼠标上浮JS显示增加按钮--------------------------
        var newCount = 0;
        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='add node' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(){
            	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            	var addTemp = new Object();
            	addTemp.name = "new node" + (++newCount);
            	addTemp.pid = treeNode.id;
            	if(1==treeNode.id){
            		addTemp.hasItem = 1;
            	}else{
            		addTemp.hasItem = 0;
            	}
                //---------------创建对象存新节点的值---------------------
    			var userCollectionsType = JSON.stringify(addTemp);
                $.post(webName+"/insert",{"userCollectionsType": userCollectionsType},function(myresult){
                	var result = $.parseJSON(myresult);
    				var reply = result.data.reply;
    				var insertID = result.data.insertID;
    				//如果在根目录下创建 则为文件夹 否则是普通节点
                	if(1==treeNode.id){
                		zTree.addNodes(treeNode, {id:insertID, pId:treeNode.id, name:"new node" + newCount,isParent:true});
                	}else{
                		zTree.addNodes(treeNode, {id:insertID, pId:treeNode.id, name:"new node" + newCount});
                	}
    				if(reply==0){
    					alert('添加失败');
    				}
    			})
                return false;
            });
        };
        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_"+treeNode.tId).unbind().remove();
        };
      //--------------鼠标上浮JS结束-------------------------- 

      //----------------展开收起JS--------------------------
		var className1 = "dark";

		function beforeCollapse(treeId, treeNode) {
			className1 = (className1 === "dark" ? "":"dark");
			return (treeNode.collapse !== false);
		}
		function onCollapse(event, treeId, treeNode) {
		}		
		function beforeExpand(treeId, treeNode) {
			className1 = (className1 === "dark" ? "":"dark");
			return (treeNode.expand !== false);
		}
		function onExpand(event, treeId, treeNode) {
		}

		function expandNode(e) {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo")
			var nodes = zTree.getNodes();
			var expandAll = true;

			for(var i=0;i<nodes.length;i++){
				expandAll = nodes[i].open;
				if(!expandAll){
					zTree.expandAll(true);
					break;
				}
			}
			if(expandAll){
				zTree.expandAll(false);
			}
		}
		//--------------------------修改---------------------------
		var className2 = "dark";
		function beforeEditName(treeId, treeNode) {
			className2 = (className2 === "dark" ? "":"dark");
			//showLog("[ "+getTime()+" beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.selectNode(treeNode);
			setTimeout(function() {
				if (confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？")) {
					setTimeout(function() {
						zTree.editName(treeNode);
					}, 0);
				}
			}, 0);
			return false;
		}
		function beforeRename(treeId, treeNode, newName, isCancel) {
			className2 = (className2 === "dark" ? "":"dark");
			if (newName.length == 0) {
				setTimeout(function() {
					var zTree = $.fn.zTree.getZTreeObj("treeDemo");
					zTree.cancelEditName();
					alert("节点名称不能为空.");
				}, 0);
				return false;
			}
			return true;
		}
		function onRename(e, treeId, treeNode, isCancel) {
			if(treeNode.name==""||treeNode.name==null){
				alert("名字不能为空！")
				return; 
			}
			var upTemp = new Object();
			upTemp.id = treeNode.id;
			upTemp.name = treeNode.name;
			upTemp.hasItem = treeNode.isParent;
			var userCollectionsType = JSON.stringify(upTemp);
			$.post(webName+"/upname",{"userCollectionsType": userCollectionsType},function(myresult){
				var result = $.parseJSON(myresult);
				var reply = result.data.reply;
				if(reply==0){
					alert('修改失败');
				}
			})
		}
		//----------------------修改结束-----------------------------
		//-----------------------删除-------------------------------
		var className3 = "dark";
		function beforeRemove(treeId, treeNode) {
			className3 = (className3 === "dark" ? "":"dark");
			//showLog("[ "+getTime()+" beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.selectNode(treeNode);
			if(treeNode.isParent){
				return confirm("确认删除父节点  [" + treeNode.name + "] 并删除它的所有子节点吗？");
			}else{
				return confirm("确认删除 节点  [" + treeNode.name + "] 吗？");
			}
		}
		function onRemove(e, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			var nodes = zTree.getNodes();
			var hasItem = false;

			$.post(webName+"/delete",{"id": treeNode.id,"isParent":treeNode.isParent},function(myresult){
				var result = $.parseJSON(myresult);
				var reply = result.data.reply;
				if(reply==0){
					alert('删除失败');
				}
			})
		}
		//-----------------------删除-------------------------------
		function showRemoveBtn(treeId, treeNode) {
			return !(treeNode.tId=="treeDemo_1");
		}
		function showRenameBtn(treeId, treeNode) {
			return !(treeNode.tId=="treeDemo_1");
		}
		//-----------------------拖拽--------------------------------
		var log, className4 = "dark", curDragNodes, autoExpandNode;
		function beforeDrag(treeId, treeNodes) {
			className4 = (className4 === "dark" ? "":"dark");
			for (var i=0,l=treeNodes.length; i<l; i++) {
				if (treeNodes[i].drag === false) {
					curDragNodes = null;
					return false;
				} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
					curDragNodes = null;
					return false;
				}
			}
			curDragNodes = treeNodes;
			return false;
		}
		function beforeDragOpen(treeId, treeNode) {
			autoExpandNode = treeNode;
			return true;
		}
		function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
			className4 = (className4 === "dark" ? "":"dark");
			
        	var dragTemp = new Object();
			dragTemp.id = targetNode.id;
    		dragTemp.hasItem = targetNode.isParent;
            //---------------创建对象存新节点的值---------------------
			var articleType = JSON.stringify(dragTemp);
			$.post(webName+"/drag",{"id": treeNodes[0].id,"articleType":articleType},function(result){
				var reply = result.data.reply;
				if(reply==0){
					alert('拖拽失败');
				}
			})
			return true;
		}
		function onDrag(event, treeId, treeNodes) {
			className4 = (className4 === "dark" ? "":"dark");
		}
		function onExpand(event, treeId, treeNode) {
			if (treeNode === autoExpandNode) {
				className4 = (className4 === "dark" ? "":"dark");
				showLog("[ onExpand ]" + treeNode.name);
			}
		}

		function setTrigger() {
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.setting.edit.drag.autoExpandTrigger = $("#callbackTrigger").attr("checked");
		}
		//------------------------点击事件----------------------
		
		var log, className = "dark";
		function beforeClick(treeId, treeNode, clickFlag) {
			if(treeNode.tId=="treeDemo_1"){
				location.href = "/cms/jsp/collection"
			}
			className = (className === "dark" ? "":"dark");
			//alert("[ beforeClick ]" + treeNode.name + treeNode.isParent + treeNode.id);
			if(treeNode.isParent){
				globalData.url = webName+"/parentid";
			}else{
				globalData.url = webName+"/typeid"
			}
			var data={};
			data["current"]=1;	
			data["size"]=globalData.size;
			data["typeID"]=treeNode.id;
			globalData.typeID = treeNode.id;
			$.getJSON(globalData.url,data,function(json){
				$blog=$("#blog-posts").html("");
				if(json.data.lists.length>0){
					successHandler(json.data.lists);//更新记录
					refreshGlobalData(json.data.page);//更新全局数据
					loadPaginator();//加载分页
				}else{
					successHandler(json.data.lists);//更新记录
					$("#pager").css("display","none");
					$blog=$("#blog-posts").html("<h2>您还需要更多收藏哦！</h2>");
				}
			});
			return (treeNode.click != false);
		}
		function onClick(event, treeId, treeNode, clickFlag) {
		}
		
		//------------------------点击事件----------------------
		
		//将配置和节点 统一初始化成ztree
		$(document).ready(function(){
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			$("#expandAll").bind("click", expandNode);
//			$("#checkAll").bind("click", checkNode);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.setting.edit.drag.autoExpandTrigger = $("#callbackTrigger").attr("checked");
		});
		
}    
 
























